import { useCallback, useEffect, useState } from 'react'

function useAwaitAsync<T>(resData: any, ready: (data: any) => boolean) {
  const [awaitList, setAwaitList] = useState<((res: T) => void)[]>([])

  const awaitAsync = useCallback(() => {
    return new Promise<T>((resolve) => { 
      const callback = (res: T) => resolve(res)
      if (!ready(resData)) { 
        setAwaitList(awaitList.concat(callback))
      } else return resolve(resData as T)
    })
  }, [resData, awaitList])

  useEffect(() => { 
    if (awaitList.length && ready(resData)) { 
      awaitList.forEach(callback => callback(resData))
      setAwaitList([])
    }
  }, [awaitList, resData])

  return { awaitAsync }
}

export default useAwaitAsync